package com.heima.wemedia.service.impl;

import cn.hutool.core.io.FileTypeUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;



    private static final List<String> IMAGE_SUFFIX_LIST = Arrays.asList("jpg","jpeg","png","bmp","gif");
    /**
     * 素材上传
     *
     * @param file
     * @return
     */
    @Override
    @Transactional
    public ResponseResult upload(MultipartFile file) {
        //1.上传图片到minio中
         if (file.isEmpty()||file.getSize()==0){
             return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
         }
         try {
             String type = FileTypeUtil.getType(file.getInputStream());
             if (!IMAGE_SUFFIX_LIST.contains(type)){
                 return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文件上传参数失效");
             }
             String fileName =IdUtil.fastSimpleUUID()+"."+type;
             String url = fileStorageService.uploadImgFile(null, fileName, file.getInputStream());
             WmMaterial wmMaterial = new WmMaterial();
             Integer id = WmThreadLocalUtil.getUser().getId();
             wmMaterial.setUserId(id);
             wmMaterial.setUrl(url);
             wmMaterial.setType(Short.parseShort("0"));
             wmMaterial.setIsCollection(Short.parseShort("0"));
             wmMaterial.setCreatedTime(new java.util.Date());
             this.save(wmMaterial);
             WmMaterial one = this.getOne(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, id).
                     orderByDesc(WmMaterial::getCreatedTime).last("limit 1"));
             return ResponseResult.okResult(one);
         } catch (IOException e) {
            e.printStackTrace();
             return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文件上传失败");
         }


    }

    /**
     * 查询素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto dto) {
       /* dto.checkParam();
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        Integer id = WmThreadLocalUtil.getUser().getId();
        this.lambdaQuery().eq(WmMaterial::getUserId, id).eq(dto.getIsCollection() > 0, WmMaterial::getIsCollection, dto.getIsCollection())
                .orderByDesc(WmMaterial::getCreatedTime).page(page);

        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());

        return ResponseResult.okResult(pageResponseResult);*/
         dto.checkParam();
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        this.lambdaQuery().eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId())
                .eq(dto.getIsCollection()>0,WmMaterial::getIsCollection,dto.getIsCollection())
                .page(page);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        pageResponseResult.setData(page.getRecords());
        return  pageResponseResult;
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult del(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmMaterial wmMaterial = this.getById(id);
        if (ObjectUtil.isEmpty(wmMaterial)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer i = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getMaterialId, id));
        if (i>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"素材被引用，删除失败");
        }
        this.removeById(id);
        // minIo删除图片
        fileStorageService.delete(wmMaterial.getUrl());
        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS, "操作成功");
    }

    /**
     * 取消收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancel(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        boolean update = this.lambdaUpdate().eq(WmMaterial::getId, id).set(WmMaterial::getIsCollection, 0).update();
        if (!update){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"取消收藏失败");
        }
        return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult collect(Integer id) {
        if (id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }


        boolean update = this.lambdaUpdate().eq(WmMaterial::getId, id).set(WmMaterial::getIsCollection, 1).update();
        if (!update){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR,"收藏失败");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
